/**
 * printf function of libdragonscript
 * Copyright (C) 2009 Hajime Yoshimori <RoarLudros@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "DragonPrintf"
#include "DragonExcept"
#include "DragonMessage"

#include <cstdio>
#include <cstdarg>
#include <cwchar>

using namespace std;

#define _(msg) (msg)

namespace dragon {
  static const size_t buf_size = 128;
  
  const DragonMessage msgPrintFormatError
  = DragonMessage(DragonMessage::error,
				  _("Print format is wrong."),
				  _("I think print format is wrong."));
}

#undef _

dragon::sprintf::sprintf(const char* fmt, ...) {
  char*  buf;
  size_t ret;
  va_list ap;
  
  buf = new char[dragon::buf_size];
  
  va_start(ap, fmt);
  ret = vsnprintf(buf, dragon::buf_size, fmt, ap);
  va_end(ap);
  if((int)ret < 0) {
	throw dragon::DragonExcept(&msgPrintFormatError);
  }
  if(ret >= buf_size) {
	delete [] buf;
	buf = new char[ret + 1];
	
	va_start(ap, fmt);
	ret = vsnprintf(buf, ret + 1, fmt, ap);
	va_end(ap);
  }
  data = "";
  data += buf;
  delete [] buf;
}

dragon::wsprintf::wsprintf(const wchar_t* fmt, ...) {
  wchar_t* buf;
  size_t   ret = (size_t)-1;
  va_list  ap;
  int      n = 1;
  
  do {
	buf = new wchar_t[dragon::buf_size * n];
	
	va_start(ap, fmt);
	ret = vswprintf(buf, dragon::buf_size * n - 1, fmt, ap);
	va_end(ap);
	if((int)ret < 0) {
	  throw dragon::DragonExcept(&msgPrintFormatError);
	}
	if(ret < dragon::buf_size * n - 1) break;
	
	n++;
	delete [] buf;
  } while(1);
  
  data = L"";
  data += buf;
  delete [] buf;
}

namespace dragon {
  std::ostream& operator<<(std::ostream& __os, sprintf __s) {
	__os << __s.data;
	return __os;
  }
  
  std::wostream& operator<<(std::wostream& __os, wsprintf __w) {
	__os << __w.data;
	return __os;
  }
};
